package com.hjy.controller;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet(name = "DownController", value = "/down")
public class DownController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取文件的真实路径
        response.setContentType("text/html; charset=UTF-8");
        String realPath = request.getServletContext().getRealPath("/WEB-INF/classes/腾讯.png");
        //项目真实路径 : E:\tomcat\apache-tomcat-8.5.31\webapps\ROOT\WEB-INF\classes\腾讯.png
        System.out.println("项目真实路径 : "+realPath);

        //获取文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //设置允许下载的消息头
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        //获取输入流和输出流
        ServletOutputStream outputStream = response.getOutputStream();
        FileInputStream inputStream = new FileInputStream(realPath);

        int len = 0;
        byte[] buffer = new byte[1024];

        while ((len = inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
